import styled from '@emotion/styled';
import { useMutation, useQuery } from '@tanstack/react-query';
import { useRouter } from 'next/router';
import { useEffect, useState } from 'react';
import {
  AdminButton,
  AdminWrapper,
  ControlArea,
  InteractiveDate,
  JSONDisplay,
  Undefined,
} from '../../../next-res/components/admin/common';
import {
  UserActivity,
  UserComposerRequest,
  UserConductorRequest,
  UserIdentity,
  UserMetrics,
  UserProject,
  UserSharedTrack,
  ZohoSyncStatus,
} from '../../../src/types/adminServerTypes.js';

const Wrapper = styled(AdminWrapper)`
  table {
    tr {
      td {
        padding: 3px;
      }
    }
    tr:nth-of-type(odd) {
      background-color: #f3f3f3;
    }
  }
`;

const UserBasicDetails = styled.div`
  margin-bottom: 20px;
  table {
    margin-top: 10px;
    tr {
      td:first-of-type {
        font-weight: bold;
        padding-right: 10px;
      }
    }
  }
`;

const UserIdentities = styled.div`
  margin-bottom: 20px;
  table {
    margin-top: 10px;
    tr {
      &.caveat {
        font-style: italic;
        color: #3286b8;
      }
      td:first-of-type {
        font-weight: bold;
        padding-right: 10px;
      }
    }
  }
`;

const UserNameNote = styled.div`
  font-style: italic;
  font-size: 14px;
  margin-top: 10px;
  color: #3286b8;
  padding: 10px;
  border: 1px solid #3286b8;
  border-radius: 5px;
  width: 400px;
`;
const UserIdentityExistanceRow = styled.div`
  display: flex;
  justify-content: space-between;
  gap: 20px;
  margin-bottom: 10px;

  span {
    flex-grow: 1;
    border-radius: 5px;
    border: 2px solid #333;
    padding: 5px 10px;
    font-size: 12px;
    text-align: center;
    cursor: pointer;

    &:hover {
      background-color: #f9f9f9;
    }

    &.enabled {
      border-color: #4caf50;
      :after {
        content: '✅';
        padding-left: 5px;
      }
    }
    &.disabled {
      border-color: #f44336;
      :after {
        content: '❌';
        padding-left: 5px;
      }
    }
  }
`;

const UserRecentActivity = styled.div`
  table {
    margin-top: 10px;
    tr {
      td:first-of-type {
        font-weight: bold;
        padding-right: 10px;
      }
    }
  }
`;

const UserActivityDetails = styled.div`
  table {
    margin-top: 10px;
    outline: 0px transparent;
    border-collapse: collapse;
    td {
      padding: 5px;
    }
    tr {
      td:first-of-type {
        font-weight: bold;
        padding-right: 10px;
      }
    }
    td.action {
      font-weight: bold;
    }
    td.type {
      span {
        padding: 5px;
        border-radius: 5px;
        font-size: 10px;
        font-weight: bold;
      }
      .frontend {
        color: white;
        background-color: #4caf50;
        border: 1px solid #4caf50;
      }
      .backend {
        color: white;
        background-color: #f44336;
        border: 1px solid #f44336;
      }
    }
  }
`;

const UserProjects = styled.div`
  table {
    outline: 0px transparent;
    border-collapse: collapse;
    margin-top: 10px;
    td {
      padding: 5px;
    }
    tr {
      td:nth-of-type(2) {
        font-weight: bold;
      }
    }
    span.pill {
      padding: 5px;
      border-radius: 5px;
      font-size: 10px;
      font-weight: bold;
      border: 1px solid #333;
      margin-right: 5px;
    }
  }
`;

const UserSharedTracks = styled.div`
  table {
    outline: 0px transparent;
    border-collapse: collapse;
    margin-top: 10px;
    td {
      padding: 5px;
    }
    tr {
      td:nth-of-type(2) {
        font-weight: bold;
      }
    }
  }
`;

const UserConductorRequests = styled.div`
  width: 100%;
  table {
    width: 100%;
    outline: 0px transparent;
    border-collapse: collapse;
    margin-top: 10px;
    td {
      padding: 5px;
    }
    tr {
      td:nth-of-type(1) {
        font-weight: bold;
      }
    }
    .title {
      font-size: 10px;
      font-weight: bold;
      font-style: italic;
      display: block;
      margin-bottom: 5px;
    }
  }
`;

const UserComposerRequests = styled.div`
  width: 100%;
  table {
    width: 100%;
    outline: 0px transparent;
    border-collapse: collapse;
    margin-top: 10px;
    td {
      padding: 5px;
    }
    tr {
      td:nth-of-type(1) {
        font-weight: bold;
      }
    }
    .title {
      font-size: 10px;
      font-weight: bold;
      font-style: italic;
      display: block;
      margin-bottom: 5px;
    }
  }
`;

const InfoIcon = styled.span`
  cursor: help;
  .icon {
    margin-left: 10px;
    display: inline-block;
    border-radius: 50%;
    width: 1.5em;
    height: 1.5em;
    text-align: center;
    line-height: 1.4em;
    font-size: 0.6em;
    border: 1px solid #ccc;
  }

  .tooltip {
    border-radius: 5px;
    font-size: 12px;
    display: none;
    position: absolute;
    background-color: #f9f9f9;
    border: 1px solid #ccc;
    padding: 5px;
    z-index: 1;
  }
  &:hover {
    .tooltip {
      display: block;
    }
  }
`;

export async function getServerSideProps(context: any) {
  const serverUri = process.env.SERVER_URI || 'http://localhost:3000';

  // Get the user's session based on the request
  if (context?.req?.user?.role !== 'admin') {
    context.res.statusCode = 404;
    context.res.end();
  }

  return {
    props: {
      serverUri,
    },
  };
}

const UserDetailsPage = ({ serverUri }: { serverUri: string }) => {
  const router = useRouter();
  const { userId } = router.query;

  const [openSection, setOpenSection] = useState<string | null>(null);
  const [openedUserActivity, setOpenedUserActivity] = useState<number | null>(null);
  const [openedProject, setOpenedProject] = useState<number | null>(null);
  const [openedConductorRequest, setOpenedConductorRequest] = useState<number | null>(null);
  const [openedDetailedConductorRequest, setOpenedDetailedConductorRequest] = useState<number | null>(null);
  const [openedComposerRequest, setOpenedComposerRequest] = useState<number | null>(null);
  const [selectedUserIdentity, setSelectedUserIdentity] = useState<UserIdentity | null>(null);

  const {
    refetch: fetchUser,
    data: user,
    isSuccess,
    isError,
  } = useQuery({
    queryKey: ['user', userId],
    queryFn: async ({ queryKey }) => {
      const [, userId] = queryKey;
      const response = await fetch(`${serverUri}/api/admin/user/${userId}`, { credentials: 'include' });
      return response.json() as unknown as UserMetrics;
    },
  });

  const { data: userZohoSyncs, refetch: fetchUserZohoSyncs } = useQuery({
    queryKey: ['userZohoSyncs', userId],
    queryFn: async ({ queryKey }) => {
      const [, userId] = queryKey;
      const response = await fetch(`${serverUri}/api/admin/zoho/recentUserSyncs/${userId}`, { credentials: 'include' });
      return (await response.json())?.data as unknown as ZohoSyncStatus[];
    },
  });

  useEffect(() => {
    if (user) {
      setSelectedUserIdentity(user.userIdentities[0]);
    }
  }, [user]);

  const { refetch: fetchUserActivity, data: userActivity } = useQuery({
    queryKey: ['userActivity', userId],
    queryFn: async ({ queryKey }) => {
      const [, userId] = queryKey;
      const response = await fetch(`${serverUri}/api/admin/user/${userId}/activity`, { credentials: 'include' });
      return response.json();
    },
    enabled: false,
  });

  const { refetch: fetchProjects, data: userProjects } = useQuery({
    queryKey: ['userProjects', userId],
    queryFn: async ({ queryKey }) => {
      const [, userId] = queryKey;
      const response = await fetch(`${serverUri}/api/admin/user/${userId}/projects`, { credentials: 'include' });
      return response.json();
    },
    enabled: false,
  });

  const { refetch: fetchSharedTracks, data: userSharedTracks } = useQuery({
    queryKey: ['userSharedTracks', userId],
    queryFn: async ({ queryKey }) => {
      const [, userId] = queryKey;
      const response = await fetch(`${serverUri}/api/admin/user/${userId}/tracks`, { credentials: 'include' });
      return response.json();
    },
    enabled: false,
  });

  const { refetch: fetchConductorRequests, data: conductorRequests } = useQuery({
    queryKey: ['conductorRequests', userId],
    queryFn: async ({ queryKey }) => {
      const [, userId] = queryKey;
      const response = await fetch(`${serverUri}/api/admin/user/${userId}/conductor`, { credentials: 'include' });
      return response.json();
    },
    enabled: false,
  });

  const { refetch: fetchComposerRequests, data: composerRequests } = useQuery({
    queryKey: ['composerRequests', userId],
    queryFn: async ({ queryKey }) => {
      const [, userId] = queryKey;
      const response = await fetch(`${serverUri}/api/admin/user/${userId}/composer`, { credentials: 'include' });
      return response.json();
    },
    enabled: false,
  });

  const { mutate: initialSyncToZoho, isLoading: isSyncingZoho } = useMutation(async () => {
    await fetch(`${serverUri}/api/admin/zoho/syncUser/${userId}`, {
      credentials: 'include',
      method: 'POST',
    });
    fetchUser();
    fetchUserZohoSyncs();
  });

  function toggleActivityDetails(index: number) {
    if (openedUserActivity === index) {
      setOpenedUserActivity(null);
    } else {
      setOpenedUserActivity(index);
    }
  }

  function toggleProjectDetails(index: number) {
    if (openedProject === index) {
      setOpenedProject(null);
    } else {
      setOpenedProject(index);
    }
  }

  function toggleConductorRequestDetails(index: number) {
    if (openedConductorRequest === index) {
      setOpenedConductorRequest(null);
      setOpenedDetailedConductorRequest(null);
    } else {
      setOpenedConductorRequest(index);
      setOpenedDetailedConductorRequest(null);
    }
  }

  function toggleComposerRequestDetails(index: number) {
    if (openedComposerRequest === index) {
      setOpenedComposerRequest(null);
    } else {
      setOpenedComposerRequest(index);
    }
  }

  if (isError) {
    return (
      <Wrapper>
        <a href="/admin" style={{ color: 'black' }}>
          Back to Admin Home
        </a>
        <br />
        Error: User not found
      </Wrapper>
    );
  }

  if (!isSuccess) {
    return (
      <Wrapper>
        <a href="/admin" style={{ color: 'black' }}>
          Back to Admin Home
        </a>
        <br />
        Loading user data...
      </Wrapper>
    );
  }

  return (
    <Wrapper>
      <div style={{ display: 'flex', justifyContent: 'left', gap: '20px', alignItems: 'baseline' }}>
        <h1>{user?.displayName || user?.email}'s Details</h1>
        <a href="/admin" style={{ color: 'black' }}>
          Back to Admin Home
        </a>
      </div>
      <ControlArea>
        <AdminButton
          onClick={() => {
            if (openSection === 'userActivity') {
              setOpenSection(null);
            } else {
              setOpenSection('userActivity');
              if (!userActivity) fetchUserActivity();
            }
          }}
        >
          {openSection === 'userActivity' ? 'Hide Activities' : 'Show Activities'}
        </AdminButton>
        <AdminButton
          onClick={() => {
            if (openSection === 'userProjects') {
              setOpenSection(null);
            } else {
              setOpenSection('userProjects');
              if (!userProjects) fetchProjects();
            }
          }}
        >
          {openSection === 'userProjects' ? 'Hide Projects' : 'Show Projects'}
        </AdminButton>
        <AdminButton
          onClick={() => {
            if (openSection === 'userSharedTracks') {
              setOpenSection(null);
            } else {
              setOpenSection('userSharedTracks');
              if (!userSharedTracks) fetchSharedTracks();
            }
          }}
        >
          {openSection === 'userSharedTracks' ? 'Hide Shared Tracks' : 'Show Shared Tracks'}
        </AdminButton>
        <AdminButton
          onClick={() => {
            if (openSection === 'conductorRequests') {
              setOpenSection(null);
            } else {
              setOpenSection('conductorRequests');
            }
            if (!conductorRequests) fetchConductorRequests();
          }}
        >
          {openSection === 'conductorRequests' ? 'Hide Conductor Requests' : 'Show Conductor Requests'}
        </AdminButton>
        <AdminButton
          onClick={() => {
            if (openSection === 'composerRequests') {
              setOpenSection(null);
            } else {
              setOpenSection('composerRequests');
            }
            if (!composerRequests) fetchComposerRequests();
          }}
        >
          {openSection === 'composerRequests' ? 'Hide Composer Requests' : 'Show Composer Requests'}
        </AdminButton>
      </ControlArea>

      <hr style={{ margin: '20px auto' }} />
      {
        // Show a loading state while the user data is being fetched
        !user && <p>Loading...</p>
      }
      {user && (
        <>
          <div
            style={{
              display: 'flex',
              flexWrap: 'wrap',
              flexDirection: 'row',
              padding: '20px',
              gap: '20px',
            }}
          >
            <UserBasicDetails>
              <h2>
                Basic Info
                <InfoIcon>
                  <span className="icon">?</span>
                  <span className="tooltip">This is the basic information about the user.</span>
                </InfoIcon>
              </h2>
              <table>
                <tbody>
                  <tr>
                    <td>UserID:</td>
                    <td>{user.userId}</td>
                  </tr>
                  <tr>
                    <td>Display Name:</td>
                    <td>{user.displayName}</td>
                  </tr>
                  <tr>
                    <td>Share Name:</td>
                    <td>{user.shareName}</td>
                  </tr>
                  <tr>
                    <td>Email:</td>
                    <td>{user.email}</td>
                  </tr>
                  <tr>
                    <td>Browser Language:</td>
                    <td>{user.browserLanguage}</td>
                  </tr>
                  <tr>
                    <td>Stripe Present:</td>
                    <td>{user.stripePresent ? 'Yes' : 'No'}</td>
                  </tr>
                  <tr>
                    <td>Paddle Present:</td>
                    <td>{user.paddlePresent ? 'Yes' : 'No'}</td>
                  </tr>
                  <tr>
                    <td>Plan:</td>
                    <td>{user.plan}</td>
                  </tr>
                  <tr>
                    <td>Plan Expiry:</td>
                    <td>
                      <InteractiveDate date={user.planExpiry} />
                    </td>
                  </tr>
                  <tr>
                    <td>Will Renew:</td>
                    <td>{user.willRenew === null ? <Undefined /> : user.willRenew ? 'Yes' : 'No'}</td>
                  </tr>
                  <tr>
                    <td>Override Plan:</td>
                    <td>
                      <Undefined value={user.overridePlan} />
                    </td>
                  </tr>
                  <tr>
                    <td>Override Expiry:</td>
                    <td>
                      <InteractiveDate date={user.overrideExpiry} />
                    </td>
                  </tr>
                </tbody>
              </table>
              <a href="/admin/planOverrides" style={{ color: 'black', paddingLeft: '5px', fontSize: '0.8em' }}>
                Edit Plan Overrides
              </a>

              <h2>
                Zoho Sync
                <InfoIcon>
                  <span className="icon">?</span>
                  <span className="tooltip">This is for debugging the Zoho sync</span>
                </InfoIcon>
                <AdminButton
                  style={{ marginLeft: '20px' }}
                  onClick={() => {
                    initialSyncToZoho();
                  }}
                >
                  {isSyncingZoho ? 'Sending...' : 'Send'}
                  <InfoIcon>
                    <span className="icon">?</span>
                    <span className="tooltip">This will insert or update a user in Zoho based on the user's email</span>
                  </InfoIcon>
                </AdminButton>
              </h2>
              {userZohoSyncs && userZohoSyncs.length > 0 ? (
                <table>
                  <thead>
                    <tr>
                      <th>ID</th>
                      <th>Sync Type</th>
                      <th>Sync Status</th>
                      <th>Timestamp</th>
                      <th>Details</th>
                    </tr>
                  </thead>
                  <tbody>
                    {userZohoSyncs.map((sync) => (
                      <tr key={sync.id}>
                        <td>{sync.id}</td>
                        <td>{sync.sync_type}</td>
                        <td>{sync.sync_status}</td>
                        <td>
                          <InteractiveDate date={sync.created_at} />
                        </td>
                        <td>
                          <a href={`/admin/zohoSync?syncId=${sync.id}`}>View</a>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              ) : (
                <p>Unknown sync status</p>
              )}

              <h2>
                Engagement Info
                <InfoIcon>
                  <span className="icon">?</span>
                  <span className="tooltip">
                    This is information pertaining to how much the user has been using the app.
                  </span>
                </InfoIcon>
              </h2>
              <table>
                <tbody>
                  <tr>
                    <td>Engagement score (all-time):</td>
                    <td>{user.engagementScoreAllTime}</td>
                  </tr>
                  <tr>
                    <td>Engagement score (past 28 days):</td>
                    <td>{user.engagementScoreRecent}</td>
                  </tr>
                  <tr>
                    <td>Meaningful Session Count:</td>
                    <td>{user.meaningfulSessionCount}</td>
                  </tr>
                  <tr>
                    <td>Unique Project Count:</td>
                    <td>{user.projectCount}</td>
                  </tr>
                  <tr>
                    <td>Share Count:</td>
                    <td>{user.shareCount}</td>
                  </tr>
                  <tr>
                    <td>Last Active:</td>
                    <td>
                      <InteractiveDate date={user.lastActive} />
                    </td>
                  </tr>
                  <tr>
                    <td>Conductor 30d:</td>
                    <td>{user.conductorUse30d}</td>
                  </tr>
                  <tr>
                    <td>Composer 30d:</td>
                    <td>{user.composerUse30d}</td>
                  </tr>
                  <tr>
                    <td>Activity 30d:</td>
                    <td>{user.activity30d}</td>
                  </tr>
                </tbody>
              </table>
            </UserBasicDetails>
            <div>
              <UserIdentities>
                <h2>
                  User Identities
                  <InfoIcon>
                    <span className="icon">?</span>
                    <span className="tooltip">This is the list of accounts the user has linked.</span>
                  </InfoIcon>
                </h2>
                <UserIdentityExistanceRow>
                  <span
                    onClick={() => {
                      const ui = user.userIdentities.find((u) => u.issuer === 'google');
                      if (ui) setSelectedUserIdentity(ui);
                    }}
                    className={user.userIdentities.some((u) => u.issuer === 'google') ? 'enabled' : 'disabled'}
                  >
                    Google
                  </span>
                  <span
                    onClick={() => {
                      const ui = user.userIdentities.find((u) => u.issuer === 'fusionauth');
                      if (ui) setSelectedUserIdentity(ui);
                    }}
                    className={user.userIdentities.some((u) => u.issuer === 'fusionauth') ? 'enabled' : 'disabled'}
                  >
                    FusionAuth
                  </span>
                  <span
                    onClick={() => {
                      const ui = user.userIdentities.find((u) => u.issuer === 'facebook');
                      if (ui) setSelectedUserIdentity(ui);
                    }}
                    className={user.userIdentities.some((u) => u.issuer === 'facebook') ? 'enabled' : 'disabled'}
                  >
                    Facebook
                  </span>
                </UserIdentityExistanceRow>

                {selectedUserIdentity ? (
                  <>
                    <table>
                      <tbody>
                        <tr>
                          <td>Issuer:</td>
                          <td>{selectedUserIdentity.issuer}</td>
                        </tr>
                        <tr>
                          <td>External ID:</td>
                          <td>{selectedUserIdentity.externalId}</td>
                        </tr>
                        <tr>
                          <td>Linked Date</td>
                          <td>
                            <InteractiveDate date={selectedUserIdentity.createdAt} />
                          </td>
                        </tr>
                        <tr>
                          <td colSpan={2}>
                            Profile Data:
                            <JSONDisplay
                              style={{
                                maxHeight: '150px',
                                width: '370px',
                              }}
                              json={selectedUserIdentity.profileData}
                            />
                          </td>
                        </tr>
                        <tr className="caveat">
                          <td>Given Name:</td>
                          <td>{selectedUserIdentity.givenName}</td>
                        </tr>
                        <tr className="caveat">
                          <td>Family Name:</td>
                          <td>{selectedUserIdentity.familyName}</td>
                        </tr>
                        <tr className="caveat">
                          <td>Full Name:</td>
                          <td>{selectedUserIdentity.fullName}</td>
                        </tr>
                      </tbody>
                    </table>
                    <UserNameNote>
                      The name of the user is extracted from the user identity and may not be accurately represented as
                      the concept of a first and last name is not universal.
                    </UserNameNote>
                  </>
                ) : (
                  <div>No identity selected</div>
                )}
              </UserIdentities>
              <UserRecentActivity>
                <h2>
                  Most Recent Usage
                  <InfoIcon>
                    <span className="icon">?</span>
                    <span className="tooltip">
                      This is a combination of activities, conductor, and composer requests. Limited to the latest 20
                    </span>
                  </InfoIcon>
                </h2>
                <table>
                  <tbody>
                    {user.recentRequests.map((request, index) => (
                      <tr key={index}>
                        <td>{request.type}</td>
                        <td>
                          <InteractiveDate date={request.timestamp} />
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </UserRecentActivity>
            </div>
            {openSection === 'userActivity' && userActivity && (
              <UserActivityDetails>
                <h2>
                  User Activity
                  <InfoIcon>
                    <span className="icon">?</span>
                    <span className="tooltip">
                      This is the past 100 user activities.
                      <br />
                      Click on each one to get more info
                    </span>
                  </InfoIcon>
                </h2>
                <table>
                  <tbody>
                    {(userActivity as UserActivity[]).map((activity, index) => (
                      <>
                        <tr
                          key={index}
                          style={{
                            backgroundColor: index % 2 === 0 ? '#f2f2f2' : '#fcfcfc',
                            cursor: 'pointer',
                          }}
                          onClick={() => toggleActivityDetails(index)}
                        >
                          <td className="type">
                            {activity.is_frontend ? (
                              <span className="frontend">Frontend</span>
                            ) : (
                              <span className="backend">Backend</span>
                            )}
                          </td>
                          <td className="action">{activity.action}</td>
                          <td>
                            <InteractiveDate date={activity.timestamp} />
                          </td>
                        </tr>
                        {index === openedUserActivity && (
                          <tr
                            key={`${index}-props`}
                            style={{
                              backgroundColor: index % 2 === 0 ? '#f2f2f2' : '#fcfcfc',
                            }}
                          >
                            <td colSpan={3}>
                              <JSONDisplay json={activity.properties} />
                            </td>
                          </tr>
                        )}
                      </>
                    ))}
                  </tbody>
                </table>
              </UserActivityDetails>
            )}
            {openSection === 'userProjects' && userProjects && (
              <UserProjects>
                <h2>
                  User Projects
                  <InfoIcon>
                    <span className="icon">?</span>
                    <span className="tooltip">This is the list of projects the user has created.</span>
                  </InfoIcon>
                </h2>
                <table>
                  <thead>
                    <tr>
                      <th>ID</th>
                      <th>Name</th>
                      <th>Tracks</th>
                      <th>Created</th>
                      <th>Updated</th>
                      <th>Properties</th>
                    </tr>
                  </thead>
                  <tbody>
                    {(userProjects as UserProject[]).map((project, index) => (
                      <>
                        <tr
                          key={index}
                          title={project.uuid}
                          style={{
                            cursor: 'pointer',
                            backgroundColor: index % 2 === 0 ? '#f2f2f2' : '#fcfcfc',
                          }}
                          onClick={() => toggleProjectDetails(index)}
                        >
                          <td>{project.id}</td>
                          <td
                            style={{
                              maxWidth: '200px',
                              overflow: 'hidden',
                              textOverflow: 'ellipsis',
                              whiteSpace: 'nowrap',
                              color: project.is_old ? 'red' : 'black',
                            }}
                          >
                            {project.name}
                          </td>
                          <td>{project.tracks}</td>
                          <td>
                            <InteractiveDate date={project.created_at} />
                          </td>
                          <td>
                            <InteractiveDate date={project.updated_at} />
                          </td>
                          <td>
                            {project.remixable && <span className="pill">Remixable</span>}
                            {project.is_remix && <span className="pill">Is Remix</span>}
                          </td>
                        </tr>
                        {index === openedProject && (
                          <tr
                            style={{
                              backgroundColor: index % 2 === 0 ? '#f2f2f2' : '#fcfcfc',
                            }}
                          >
                            <td colSpan={6} className="moreInfo">
                              <span
                                style={{
                                  fontSize: '12px',
                                  marginRight: '5px',
                                }}
                              >
                                {project.uuid}
                              </span>
                              {project.is_old && <span className="pill">Superceded by: {project.new_id}</span>}
                            </td>
                          </tr>
                        )}
                      </>
                    ))}
                  </tbody>
                </table>
              </UserProjects>
            )}

            {openSection === 'userSharedTracks' && userSharedTracks && (
              <UserSharedTracks>
                <h2>
                  Shared Tracks
                  <InfoIcon>
                    <span className="icon">?</span>
                    <span className="tooltip">This is the list of tracks the user has shared.</span>
                  </InfoIcon>
                </h2>
                <table>
                  <thead>
                    <tr>
                      <th>ID</th>
                      <th>Name</th>
                      <th>UUID</th>
                      <th>Created</th>
                    </tr>
                  </thead>
                  <tbody>
                    {(userSharedTracks as UserSharedTrack[]).map((track, index) => (
                      <tr key={index} style={{ backgroundColor: index % 2 === 0 ? '#f2f2f2' : '#fcfcfc' }}>
                        <td>{track.id}</td>
                        <td>{track.name}</td>
                        <td>
                          <a href={`/tracks/${track.uuid}`}>{track.uuid}</a>
                        </td>
                        <td>
                          <InteractiveDate date={track.created_at} />
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </UserSharedTracks>
            )}
            {openSection === 'conductorRequests' && conductorRequests && (
              <UserConductorRequests>
                <h2>
                  Conductor Requests
                  <InfoIcon>
                    <span className="icon">?</span>
                    <span className="tooltip">This is the latest 200 conductor requests the user has made.</span>
                  </InfoIcon>
                </h2>
                <table>
                  <thead>
                    <tr>
                      <th>Request</th>
                      <th>Response Time</th>
                      <th>Timestamp</th>
                    </tr>
                  </thead>
                  <tbody>
                    {(conductorRequests as UserConductorRequest[]).map((request, index) => (
                      <>
                        <tr
                          key={index}
                          style={{ backgroundColor: index % 2 === 0 ? '#f2f2f2' : '#fcfcfc', cursor: 'pointer' }}
                          onClick={() => toggleConductorRequestDetails(index)}
                        >
                          <td>{request.request}</td>
                          <td>{request.response_time_ms / 1000}s</td>
                          <td>
                            <InteractiveDate date={request.created_at} />
                          </td>
                        </tr>
                        {index === openedConductorRequest && (
                          <tr
                            key={`${index}-response`}
                            style={{ backgroundColor: index % 2 === 0 ? '#f2f2f2' : '#fcfcfc' }}
                          >
                            <td colSpan={3}>
                              <span className="title">Response</span>
                              <JSONDisplay json={request.response} />
                              {index !== openedDetailedConductorRequest && (
                                <a
                                  href="#"
                                  style={{
                                    display: 'block',
                                    textAlign: 'center',
                                    fontSize: '12px',
                                    color: 'blue',
                                    textDecoration: 'underline',
                                  }}
                                  onClick={(e) => {
                                    e.preventDefault();
                                    setOpenedDetailedConductorRequest(index);
                                  }}
                                >
                                  Show More Details
                                </a>
                              )}
                            </td>
                          </tr>
                        )}
                        {index === openedDetailedConductorRequest && (
                          <tr
                            key={`${index}-detailed`}
                            style={{ backgroundColor: index % 2 === 0 ? '#f2f2f2' : '#fcfcfc' }}
                          >
                            <td colSpan={3}>
                              <span className="title"> Context</span>

                              <JSONDisplay json={request.context} />
                              <span className="title">Session Context</span>

                              <JSONDisplay json={request.session_context} />
                            </td>
                          </tr>
                        )}
                      </>
                    ))}
                  </tbody>
                </table>
              </UserConductorRequests>
            )}

            {openSection === 'composerRequests' && composerRequests && (
              <UserComposerRequests>
                <h2>
                  Composer Requests
                  <InfoIcon>
                    <span className="icon">?</span>
                    <span className="tooltip">This is the latest 200 composer requests the user has made.</span>
                  </InfoIcon>
                </h2>
                <table>
                  <thead>
                    <tr>
                      <th>UUID</th>
                      <th>Response Time</th>
                      <th>Timestamp</th>
                    </tr>
                  </thead>
                  <tbody>
                    {(composerRequests as UserComposerRequest[]).map((request, index) => (
                      <>
                        <tr
                          key={index}
                          style={{ backgroundColor: index % 2 === 0 ? '#f2f2f2' : '#fcfcfc', cursor: 'pointer' }}
                          onClick={() => toggleComposerRequestDetails(index)}
                        >
                          <td>{request.uuid}</td>
                          <td>{request.response_time_ms / 1000}s</td>
                          <td>
                            <InteractiveDate date={request.created_at} />
                          </td>
                        </tr>
                        {index === openedComposerRequest && (
                          <tr
                            key={`${index}-detail`}
                            style={{ backgroundColor: index % 2 === 0 ? '#f2f2f2' : '#fcfcfc' }}
                          >
                            <td colSpan={3}>
                              <span className="title">Request</span>
                              <JSONDisplay json={request.request} />
                              <span className="title">Response</span>
                              <JSONDisplay json={request.response} />
                            </td>
                          </tr>
                        )}
                      </>
                    ))}
                  </tbody>
                </table>
              </UserComposerRequests>
            )}
          </div>
        </>
      )}
    </Wrapper>
  );
};

export default UserDetailsPage;
